package com.ellecity06.cwhiskymall.ui.home

import androidx.fragment.app.Fragment
import androidx.lifecycle.viewModelScope
import com.ellecity06.common.base.BaseMviViewModel
import com.ellecity06.common.ktx.postEvent
import com.ellecity06.cwhiskymall.bean.request.AppMenuSettingRequest
import com.ellecity06.cwhiskymall.bean.response.AppMenuSettingRespone
import com.ellecity06.cwhiskymall.http.request
import com.ellecity06.cwhiskymall.storage.UserStorage
import com.ellecity06.cwhiskymall.ui.home.good.GoodFragment
import kotlinx.coroutines.launch

/**
 * @author ellecity06
 * @time 2024/10/22 14:49
 * @des
 */
class HomeViewModel : BaseMviViewModel<HomeState, HomeIntent>() {
    private var brandId: Int? = null
    private var xiaofeiID: Int? = null
    private var zhuanTiId: Int? = null
    private var juhuasuanID: Int? = null
    private var dionysusZoneId: Int? = null

    private var newerData: AppMenuSettingRespone.SettingWebLayoutVOS? = null
  private  var bannerItem: AppMenuSettingRespone.SettingWebLayoutVOS? = null
    // 酒神专区
    private var dionysusZone: AppMenuSettingRespone.SettingWebLayoutVOS? = null
    private var xiaofeiData: AppMenuSettingRespone.SettingWebLayoutVOS? = null
    override suspend fun collectIntent(it: HomeIntent) {
        when (it) {
            // 获取首页数据
            is HomeIntent.FetchHomeData -> fetchHome()
            is HomeIntent.FetchSurplus -> fetchSurplus()
            is HomeIntent.ReceiveWelfare -> receiveWelfare()
            is HomeIntent.SwitchMenu -> switchMenu(it.item.id)
            is HomeIntent.UpdateUser -> fetchUser()
            else -> {}
        }
    }

    /**
     * 切换菜单
     */
    private fun switchMenu(brandId: Int?) {
        this.brandId = brandId
    }

    private fun receiveWelfare() {
        request(api = { receiveWelfare() }, success = {
            mState.postEvent(HomeState.ReceiveSuccess)
            fetchSurplus()
            fetchUser()

        })
    }

    private fun fetchUser() {
        request(api = { userInfo() }, success = {
            if (it != null) {
                // 判断一下状态是否有变化
                if ( UserStorage.user?.unlockStatus!=it.unlockStatus){
                    handleBannerData()
                }
                UserStorage.user = it
                val isVip: Boolean = it.unlockStatus != 0
                if (isVip) {
                    xiaofeiData?.let {
                        mState.postEvent(HomeState.NewerData(it))
                    }
                } else {
                    newerData?.let {
                        mState.postEvent(HomeState.NewerData(it))
                    }
                }

                mState.postEvent(HomeState.FetchUserSuccess)
            }

        }, error = {

        })
    }

    /**
     * 获取剩余可领取贡献值
     */
    private fun fetchSurplus() {
        request(api = { surplusContribution() }, success = {
            it?.let {
                mState.postEvent(HomeState.SurplusContribution(it))
//                fetchSurplus()
            }
        })
    }

    private var newerCategoryId: Int? = null
    fun getNewerCategoryId(): Int? {
        return if (UserStorage.isVip()) xiaofeiID else newerCategoryId
    }

    fun getJuHuaSuanId(): Int? {
        return juhuasuanID
    }

    fun getZuanTiId(): Int? {
        return zhuanTiId
    }

    fun getDionysusZoneId(): Int {
        return  dionysusZoneId?:0
    }
    private var isLoad = false
    /**
     * 获取首页数据
     */
    private fun fetchHome() {
        request(api = { appMenuSetting(AppMenuSettingRequest()) }, success = {
            if (it != null) {
                val settingWebLayoutVOS = it.settingWebLayoutVOS
                if (settingWebLayoutVOS != null && settingWebLayoutVOS.isNotEmpty()) {

                    for (item in settingWebLayoutVOS) {
                        when (item.code) {
                            // 酒神专区
                            "dionysus_zone" -> {
                                if (!item.detailVOList.isNullOrEmpty()) {
                                    dionysusZone = item
                                    dionysusZoneId = item.detailVOList[0].settingId
                                }
                                // 没解锁过才显示新人单
                                if (!dionysusZone!!.detailVOList!!.isNullOrEmpty() && UserStorage.isHasUp()){
//                                    mState.postEvent(HomeState.DionysusData(dionysusZone!!.detailVOList!![0]))
                                    if (!isLoad){
                                        isLoad = true
                                        mState.postEvent(HomeState.ShowActivityDialog(dionysusZone!!.detailVOList!![0]))
                                    }
                                }

                            }
                            // 新人首单
                            "newpeople_first_order" -> {
                                if (item.detailVOList != null && item.detailVOList.isNotEmpty()) {
                                    newerCategoryId = item.detailVOList[0].settingId
                                    newerData = item
                                }
                                // 没解锁过才显示新人单
                                if (!UserStorage.isVip())
                                    mState.postEvent(HomeState.NewerData(item))
                            }

                            "consumption_subsidy" -> {
                                // 消费补贴
                                val detailVOList = item.detailVOList
                                if (detailVOList !== null && detailVOList.isNotEmpty()) {

                                    xiaofeiID = detailVOList[0].settingId
                                    xiaofeiData = item
                                    // 已经是vip表示解锁了，所以显示消费补贴
                                    if (UserStorage.isVip())
                                        mState.postEvent(HomeState.NewerData(item))

                                }
                            }
                            // 金刚区
                            "home_category_list" -> {
                                mState.postEvent(HomeState.CategoryData(item))
                            }
                            // 自营爆款
                            "ju_hua_suan" -> {
                                val detailVOList = item.detailVOList
                                if (detailVOList !== null && detailVOList.isNotEmpty()) {
                                    juhuasuanID = detailVOList[0].settingId
                                }
                                mState.postEvent(HomeState.SelfStoreData(item))
                            }
                            // 广告位-banner
                            "buy_alcohol_give_contribution" -> {
                                bannerItem= item
//                                mState.postEvent(HomeState.BannerData(item))
//                                val detailVOList = item.detailVOList
//                                if (detailVOList != null && detailVOList.isNotEmpty()) {
//                                    zhuanTiId = detailVOList[0].settingId
//                                    mState.postEvent(HomeState.Adv1Data(detailVOList[0]))
//                                }

                            }
                            // 专题菜单
                            "home_special_list" -> {
                                val detailVOList = item.detailVOList
                                if (detailVOList !== null && detailVOList.isNotEmpty()) {
                                    // 默认选中第一个
                                    detailVOList[0].checked = true
                                    val fragmens = mutableListOf<Fragment>()
                                    detailVOList.forEach { item ->
                                        fragmens.add(GoodFragment.newInstance(item.settingId ?: 0))
                                    }
                                    mState.postEvent(HomeState.MenuTabData(detailVOList, fragmens))

                                    switchMenu(detailVOList[0].id)
                                }

                            }

                        }

                    }
                    handleBannerData()
                    mState.postEvent(HomeState.Success)
                }
            }
        }, error = {
            viewModelScope.launch {
                showToast(it.message ?: "服务异常")
                mState.postEvent(HomeState.Error)
            }

        })
    }

    private suspend fun handleBannerData() {
        val bannerList = mutableListOf<AppMenuSettingRespone.SettingWebLayoutVOS.DetailVO>()
        if (bannerItem?.detailVOList != null) bannerList.addAll(bannerItem!!.detailVOList!!)
        // 将酒神数据新增到banner里
        if (UserStorage.isHasUp() && dionysusZone?.detailVOList != null && dionysusZone?.detailVOList!!.isNotEmpty()) {
            val detailVO = dionysusZone?.detailVOList!![0]
            detailVO.myJumpType = 2
            bannerList.add(detailVO)
        }
        if (UserStorage.isHasUp()) {
            bannerList.add(AppMenuSettingRespone.SettingWebLayoutVOS.DetailVO(myJumpType = 3))
        }
        // 将新人首单数据新增到banner里
        if (UserStorage.isVip() && newerData?.detailVOList != null && newerData?.detailVOList!!.isNotEmpty()) {
            val detailVO = newerData?.detailVOList!![0]
            detailVO.myJumpType = 1
            bannerList.add(detailVO)
        }

        mState.postEvent(HomeState.BannerData(bannerList))
    }
}